<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Biji extends Model
{
	/**
	 * 关联到模型的数据表
	 *
	 * @var string
	 */
	protected $table = 'dqm_biji';

	/**
	 * The attributes that are mass assignable.
	 *
	 * @var array
	 */
	protected $fillable = [
		'biji_title', 'biji_content', 'trash', 'share'
	];

	const FIELD_USER_ID = 'user_id';
	const FIELD_BOOK_ID = 'book_id';
	const FIELD_BIJI_TITLE = 'biji_title';
	const FIELD_BIJI_CONTENT = 'biji_content';
	const FIELD_TRASH = 'trash';
	const FIELD_SHARE = 'share';

	/**
	 * 笔记删除状态: 1、标记删除 ; 0、正常
	 */
	const ENABLE_TRASH_STATUS = 1;
	const DISABLE_TRASH_STATUS = 0;


	/**
	 * 笔记分享状态: 1、分享 ; 0、私人
	 */
	const ENABLE_SHARE_STATUS = 1;
	const DISABLE_SHARE_STATUS = 0;

	/**
	 * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
	 */
	public function user(){
		return $this->belongsTo('App\User');
	}

	/**
	 * 获取指定用户下的所有正常(无被标记删除)的笔记信息，并按指定排序方式排序
	 *
	 * @param $user_id
	 * @param $sort_type
	 * @return null
	 */
	static public function get_bijis_by_user_id($user_id, $sort_type){
		if(!empty($user_id)){
			$condition['where'] = array(self::FIELD_TRASH=>self::DISABLE_TRASH_STATUS, self::FIELD_USER_ID=>$user_id);
			$select['fields'] = array('biji_id', 'book_id', 'tag_id', 'biji_title', 'biji_content', 'created_time', 'updated_time');
			switch ($sort_type) {
				case 'earliest_created':
					$condition['order_field'] = 'created_time';
					$condition['order_sort'] = 'asc';
					break;
				case 'newest_created' :
					$condition['order_field'] = 'created_time';
					$condition['order_sort'] = 'desc';
					break;
				case 'earliest_updated':
					$condition['order_field'] = 'updated_time';
					$condition['order_sort'] = 'asc';
					break;
				case 'newest_updated':
					$condition['order_field'] = 'updated_time';
					$condition['order_sort'] = 'desc';
					break;
				case 'asc_title':
					$condition['order_field'] = 'biji_title';
					$condition['order_sort'] = 'asc';
					break;
				case 'desc_title':
					$condition['order_field'] = 'biji_title';
					$condition['order_sort'] = 'desc';
					break;
				default:
					$condition['order_field'] = 'created_time';
					$condition['order_sort'] = 'asc';
			}
			$result = Biji::select($select['fields'])->where($condition['where'])->orderBy($condition['order_field'], $condition['order_sort'])->get();
			if($result){
				return $result;
			}
		}
		return null;
	}

	/**
	 * 获取当前笔记本下的笔记列表
	 *
	 * @param $book_id
	 * @return null
	 */
	static public function get_bijis_by_book_id($book_id){
		if(!empty($book_id)){
			$condition['where'] = array(self::FIELD_BOOK_ID=>$book_id);
			$select['fields'] = array('biji_id', 'book_id', 'tag_id', 'biji_title', 'biji_content', 'created_time', 'updated_time');
			$result = Biji::select($select['fields'])->where($condition['where'])->get();
			return $result;
		}
		return null;

	}
}
